#!/bin/bash
#nohup java -jar -Duser.dir=/usr/local/project /usr/local/project/networkManagement.jar > /usr/local/project/out.log 2>&1 &
#chmod 777 /usr/local/project/out.log
#jar������
AppName=adapterClient
#jar��·��
APP_HOME=/home/tuners/adapterClient/
#JVM����
JVM_OPTS="-Dname=$AppName -Duser.dir=$APP_HOME"
#tail�˳��ؼ���
EXIT_TAIL_KEYWORD="Started AdapterClientApplication in"
if [ "$1" = "" ];
then
    echo -e "\033[0;31m δ��������� \033[0m  \033[0;34m {start|stop|restart|status} \033[0m \033[0;32mĬ��ʹ�� restart\033[0m"
    #exit 1
fi

if [ "$AppName" = "" ];
then
    echo -e "\033[0;31m δ����Ӧ���� \033[0m"
    exit 1
fi

start()
{
    PID=$(pgrep -f "$AppName".jar)
	if [ x"$PID" != x"" ]; then
	    echo "$AppName is running..."
	else
		cd $APP_HOME
		nohup java -jar  "$JVM_OPTS" $AppName'.jar' > "$APP_HOME"logs/$AppName.log 2>&1 & 2>&1 &
		echo "Start $AppName success..."
		tail -f "$APP_HOME"logs/$AppName.log| sed "/$EXIT_TAIL_KEYWORD/ q"
	fi
}

stop()
{
    echo "Stop $AppName"

	PID=""
	query(){
		PID=$(pgrep -f "$AppName".jar)
	}

	query
	if [ x"$PID" != x"" ]; then
		kill -TERM "$PID"
		echo "$AppName (pid:$PID) exiting..."
		while [ x"$PID" != x"" ]
		do
			sleep 1
			query
		done
		echo "$AppName exited."
	else
		echo "$AppName already stopped."
	fi
}

restart()
{
    stop
    sleep 2
    start
}

status()
{
    PID=$(pgrep -f "$AppName".jar)
    if [ "$PID" ];then
        echo "$AppName is running..."
    else
        echo "$AppName is not running..."
    fi
}

case $1 in
    start)
    start;;
    stop)
    stop;;
    restart)
    restart;;
    status)
    status;;
    *)
    restart;;
esac
